package com.njitzx.aop;

import cn.hutool.core.thread.ThreadUtil;
import com.njitzx.annotation.Log;
import com.njitzx.annotation.Type;
import com.njitzx.entity.dto.LoginDTO;
import com.njitzx.entity.po.LoginLog;
import com.njitzx.entity.vo.Result;
import com.njitzx.service.LoginLogService;
import com.njitzx.util.BaseContext;
import com.njitzx.util.IpUtil;
import org.apache.poi.ss.formula.functions.T;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import java.time.LocalDateTime;

@Component
@Aspect
public class LoginLogsAspect {

    @Autowired
    LoginLogService loginLogService;


    //成功的进入成功的切点  失败的进入失败的切点

    @AfterReturning(returning = "jsonResult", pointcut = "@annotation(log)")
    public void doAfterReturning(JoinPoint joinPoint, Type log, Result jsonResult) {
        //调用处理日志的方法
        handleLog(joinPoint, log, null, jsonResult);
    }

    @AfterThrowing(pointcut = "@annotation(log)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Type log, Exception e) {
        handleLog(joinPoint, log, e, null);
    }

    private void handleLog(JoinPoint joinPoint, Type log, Exception e, Result jsonResult) {

        Object[] args = joinPoint.getArgs();
        LoginDTO LoginDTO = (LoginDTO) args[0];

        // 获取当前请求的属性，包括HttpServletRequest对象。
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 如果请求属性为空，则直接返回，不处理日志。
        if (requestAttributes == null) {
            return;
        }
        // 将请求属性转换为ServletRequestAttributes，以便获取HttpServletRequest对象。
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        // 获取HttpServletRequest对象。
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String msg = null;
        String loginStatus = null;
        if (e != null) {
            msg = e.getMessage();
            loginStatus = "1";
        } else {
            msg = jsonResult.getMsg();
            loginStatus = "0";
        }

        String ipAddr = IpUtil.getIpAddress(request);
        String userAgent = request.getHeader("User-Agent");

        String browser = extractBrowserInfo(userAgent);
        String os = extractOsInfo(userAgent);

        LoginLog loginLog = LoginLog.builder()
                .userName(LoginDTO.getUsername())  //后面根据百度的api ip地址转为实际的地址
                .ipaddr(ipAddr).loginLocation("局域网").browser(browser).os(os).status(loginStatus)
                .msg(msg).loginTime(LocalDateTime.now()).build();
        System.out.println(loginLog);
        loginLogService.add(loginLog);
    }


    private String extractBrowserInfo(String userAgent) {
        if (userAgent.contains("Chrome")) {
            return "Chrome";
        } else if (userAgent.contains("Firefox")) {
            return "Firefox";
        } else if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            return "Internet Explorer";
        }
        // 添加其他浏览器的检测逻辑
        return "Unknown Browser";
    }

    private String extractOsInfo(String userAgent) {
        if (userAgent.contains("Windows NT 10.0")) {
            return "Windows 10";
        } else if (userAgent.contains("Windows NT 6.1")) {
            return "Windows 7";
        } else if (userAgent.contains("Mac OS X")) {
            return "Mac OS X";
        } else if (userAgent.contains("Linux")) {
            return "Linux";
        }
        // 添加其他操作系统的检测逻辑
        return "Unknown OS";
    }
}
